#include<func.h>
//子线程等待在对应的条件变量上,当前演示的是超时
typedef struct{
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}data_t;

void* thread_func(void* p)
{
    printf("I am child thread,will wait\n");
    struct timespec abstime;
    abstime.tv_sec=time(NULL)+4;//4秒后超时
    abstime.tv_nsec=0;
    data_t* d=(data_t*)p;
    int ret=pthread_mutex_lock(&d->mutex);//加锁
    //THREAD_ERR_CHECK(ret,"pthread_mutex_lock");
    int result=pthread_cond_timedwait(&d->cond,&d->mutex,&abstime);//解锁，将线程挂起阻塞，待signal唤醒后加锁
    //THREAD_ERR_CHECK(ret,"pthread_cond_timedwait");
    ret=pthread_mutex_unlock(&d->mutex);//解锁
    //THREAD_ERR_CHECK(ret,"pthread_mutex_unlock")
    printf("I am child thread,wakeup,timewait ret=%d start work\n",result);
    pthread_exit(NULL);
}

int main()
{
    data_t d;
    int ret=pthread_mutex_init(&d.mutex,NULL);//初始化锁
    THREAD_ERR_CHECK(ret,"pthread_mutex_init");
    ret=pthread_cond_init(&d.cond,NULL);
    THREAD_ERR_CHECK(ret,"pthread_cond_init")
    pthread_t pthid;
    ret=pthread_create(&pthid,NULL,thread_func,&d);//创建线程
    //THREAD_ERR_CHECK(ret,"pthread_create");
    sleep(6);
    ret=pthread_cond_signal(&d.cond);//唤醒子线程
    THREAD_ERR_CHECK(ret,"pthread_cond_signal")
    ret=pthread_join(pthid,NULL);//等待子线程
    THREAD_ERR_CHECK(ret,"pthread_join")
    printf("I am main thread\n");
    return 0;
}